import 'dart:async';
import 'dart:developer';
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/record/channel_logic.dart';
import 'package:ball_lion/entity/record/recent_channel_entity.dart';
import 'package:ball_lion/server/api/record_api.dart';
import 'package:ball_lion/server/api/user_api.dart';
import 'package:ball_lion/utils/sp_utils.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/entity/record/channel_entity.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/module/record/player_page.dart';
import 'package:ball_lion/module/record/points_page.dart';
import 'package:ball_lion/module/record/schedule_page.dart';
import 'package:ball_lion/module/record/team_page.dart';
import 'package:ball_lion/module/record/transfer_page.dart';
import 'package:ball_lion/widgets/bottom_picker_widget.dart';

class LeagueChannelLogic extends GetxController
    with GetTickerProviderStateMixin {
  late TabController controller;
  late final ChannelLogic channel;
  int sportsId = (Get.parameters['type'].toInt() ?? 0) + 1;
  List typeList = ["积分", "赛程", "球员", "球队", "转会"];
  ChannelEntity? _entity;
  bool isLoading = true;
  int random = math.Random().nextInt(10000000);
  String season = "";
  int seasonId = 0;
  int channelId = 0;
  int _seasonIndex = 0;
  int _typeIndex = 0;

  List<Widget> page = [];

  int get seasonIndex => _seasonIndex;
  int get typeIndex => _typeIndex;
  String get progress {
    if (_entity?.progress != null) {
      if (_entity!.progress! <= 0) {
        return "赛季未开始\u2000";
      } else if (_entity!.progress! >= 100) {
        return "100%";
      } else {
        return "${_entity!.progress}%";
      }
    }
    return "赛季未开始\u2000";
  }

  ChannelEntity? get entity => _entity;

  set typeIndex(int value) {
    _typeIndex = value;
    update();
  }

  @override
  void onInit() {
    super.onInit();
    controller = TabController(length: typeList.length, vsync: this);
  }

  @override
  void onReady() async {
    await requestData();
    if (_entity != null) {
      SpUtils.setMatchRecent(
          RecentChannelEntity.fromEntity(_entity!), sportsId);
    }
    super.onReady();
  }

  Future getData() async {
    try {
      _entity =
          await RecordApi.getChannel(Get.arguments.toString(), sportsId - 1);
    } catch (e) {
      log("---------------------$e");
    }
    update();
  }

  Future requestData() async {
    await getData();
    _typeIndex = 0;
    season = _entity?.seasonList?[_seasonIndex] ?? "";
    seasonId = _entity?.seasonIdList?[_seasonIndex].toInt() ?? 0;
    channelId = _entity?.channelId ?? 0;
    channel = Get.put(ChannelLogic(), tag: "$channelId$random");
    channel.season = season;
    channel.seasonId = seasonId;
    channel.recordType = sportsId - 1;
    await getPage();
    update();
  }

  void setIndex(value) {
    _typeIndex = value;
    update();
  }

  Future getPage() async {
    page.replaceAll([
      PointsPage(leagueId: channelId, tag: "$channelId$random"),
      SchedulePage(leagueId: channelId, tag: "$channelId$random"),
      PlayerPage(channelId, tag: "$channelId$random"),
      TeamPage(channelId, tag: "$channelId$random"),
      if (_entity?.transfer == 1)
        ZqTransferPage(channelId, tag: "$channelId$random")
    ]);
    typeList
        .replaceAll(["积分", "赛程", "球员", "球队", if (_entity?.transfer == 1) "转会"]);
    if (Get.parameters["index"] != null)
      _typeIndex = int.parse(Get.parameters["index"]!);
    controller.dispose();
    controller = TabController(
        length: typeList.length, vsync: this, initialIndex: _typeIndex);
    isLoading = false;
    update();
  }

  Future showDatePicker() async {
    _seasonIndex = await Get.bottomSheet(BottomPickerWidget(
      _entity?.seasonList
              ?.map((e) => e.length > 4
                  ? ("${e.substring(2, 4)}/${e.substring(7, 9)}")
                  : e)
              .toList() ??
          [],
      title: '选择赛季',
      initialIndex: _seasonIndex,
    ));
    season = _entity?.seasonList?[_seasonIndex] ?? "";
    seasonId = _entity?.seasonIdList?[_seasonIndex].toInt() ?? 0;
    channel.season = season;
    channel.seasonId = seasonId;
    getPage();
    update();
  }

  Future onFocus() async {
    int? result;
    if (entity?.isFocus == 1) {
      final r = await WidgetUtils.alertQuery('确认不再关注？');
      if (r == false) return;
      result = await UserApi.unFocusChannel(entity?.channelId, sportsId);
      if (result == 200) {
        Utils.onEvent('data_match_event_follow',
            params: {'event_id': entity?.channelId, "follow": 0});
        Toast.text("取消关注成功");
        getData();
      } else {
        Toast.text("取消关注失败");
      }
    } else {
      Utils.onEvent('data_match_event_follow',
          params: {'event_id': entity?.channelId, "follow": 1});
      result = await UserApi.focusChannel(entity?.channelId, sportsId);
      if (result == 200) {
        Toast.text("关注成功");
        getData();
      }
    }
  }
}
